package engine.util;

import java.io.BufferedReader;
import java.io.FileReader;
import static org.lwjgl.opengl.GL20.*;

public class ShaderUtil
{
    
    //<editor-fold defaultstate="collapsed" desc="Singleton">
    private static ShaderUtil singleton;
    
    public static ShaderUtil get()
    {
        if (singleton == null)
        {
            singleton = new ShaderUtil();
        }
        return singleton;
    }
    //</editor-fold>
    
    private static final String FILE_PATH = "shaders/";
    private static final String FILE_TYPE_VERT = ".vert";
    private static final String FILE_TYPE_FRAG = ".frag";
    
    
    private ShaderUtil()
    {
    }
    
    public int createShaderProgram()
    {
        int programID = glCreateProgram();
        if (programID < 0)
        {
            System.out.println("Failure creating a shader program.");
            System.exit(1);
        }
        return programID;
    }
    
    public int createVertShader(String fileName)
    {
        int vertShaderID = glCreateShader(GL_VERTEX_SHADER);
        if (vertShaderID == 0) 
        {
            return 0;
        }
        String vertexCode = "";
        String line;
        try
        {
            BufferedReader reader = new BufferedReader(
                new FileReader(
                    ShaderUtil.FILE_PATH + fileName + ShaderUtil.FILE_TYPE_VERT
                )
            );
            while ((line = reader.readLine()) != null)
            {
                vertexCode += line + "\n";
            }
        }
        catch (Exception e)
        {
            System.out.println("Failure creating the vertex shader: " + fileName);
            System.out.println(e);
            System.exit(1);
        }
        glShaderSource(vertShaderID, vertexCode);
        glCompileShader(vertShaderID);
        return vertShaderID;
    }

    public int createFragShader(String fileName) 
    {
        int fragShaderID = glCreateShader(GL_FRAGMENT_SHADER);
        if (fragShaderID == 0) 
        {
            return 0;
        }
        String fragCode = "";
        String line;
        try 
        {
            BufferedReader reader = new BufferedReader(
                new FileReader(
                    ShaderUtil.FILE_PATH + fileName + ShaderUtil.FILE_TYPE_FRAG
                )
            );
            while ((line = reader.readLine()) != null) 
            {
                fragCode += line + "\n";
            }
        } 
        catch (Exception e) 
        {
            System.out.println("Failure creating the fragment shader: " + fileName);
            System.out.println(e);
            System.exit(1);
        }
        glShaderSource(fragShaderID, fragCode);
        glCompileShader(fragShaderID);
        return fragShaderID;
    }
    
}
